<template>
  <div class="btn-date-2">
    <el-date-picker
      v-model="selectDates"
      type="daterange"
      unlink-panels
      range-separator="~"
      start-placeholder="开始日期"
      end-placeholder="结束日期"
      :shortcuts="shortcuts"
      @change="onChange"
    />
  </div>
</template>

<script setup>
// 把星期一设为每行的第一列
// import "dayjs/locale/zh-cn";
import dayjs from "dayjs";
dayjs.locale("zh-cn");
import { formatDate, getDateByTimeUnit } from "@/utils/utils.js";
const emit = defineEmits(["update:start", "update:end", "reload"]);
import { ref, defineProps, defineEmits } from "vue";

const allTypes = [
  {
    value: "week",
    name: "本周",
  },
  {
    value: "month",
    name: "本月",
  },
  {
    value: "quarter",
    name: "本季",
  },
  {
    value: "year",
    name: "本年",
  },
  {
    value: "last_week",
    name: "近7天",
  },
  {
    value: "last_month",
    name: "近30天",
  },
  {
    value: "last_quarter",
    name: "近90天",
  },
];

const props = defineProps({
  start: {
    type: String,
    required: true,
  },
  end: {
    type: String,
    required: true,
  },
  defaultType: {
    type: String,
    required: false,
    default: "month",
  },
  showTypes: {
    type: Array,
    required: false,
    default: () => [
      "week",
      "month",
      "quarter",
      "year",
      "last_week",
      "last_month",
      "last_quarter",
      "last_year",
      "range",
    ],
  },
});

const localStart = ref(props.start);
const localEnd = ref(props.end);
console.log("localStart: ", localStart.value);
const selectDates = ref([localStart.value, localEnd.value]);

const shortcuts = allTypes
  .filter((item) => props.showTypes.includes(item.value))
  .map((item) => ({
    text: item.name,
    value: () => {
      const { startDate, endDate } = getDateByTimeUnit(item.value);
      return [startDate, endDate];
    },
  }));

const onChange = (value) => {
  localStart.value = value[0];
  localEnd.value = value[1];
  const localDt = {
    startTime: formatDate(value[0], "yyyy-MM-dd") + " 00:00:00",
    endTime: formatDate(value[1], "yyyy-MM-dd") + " 23:59:59",
  };
  emit("update:start", localDt.startTime);
  emit("update:end", localDt.endTime);
  emit("reload", localDt);
};
</script>

<style lang="less" scoped>
.btn-date-2 {
  --el-date-editor-width: 80px;
  margin-right: 12px;

  :deep(.el-range-editor) {
    width: 220px;
  }
}
</style>
